import { _pick, isUndefined } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
import {
  listStoreEndorseRequestWithUserInfosByStoreID,
  auditStoreEndorseRequest,
} from "../../service/storeEndorseRequestService";
import AuditResult, { isAuditResult } from "../../bg-enums/auditResult";
const router = createStoreApiMWRouter();

// 获取门店代言人申请列表
router.get(
  "/sto/:storeId/endorseRequests",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { storeId } = ctx.params;
    const { userId, limit, offset, ts } = ctx;
    let isWaitAudit =
      isUndefined(ctx.query.isWaitAudit) || ctx.query.isWaitAudit === "true";

    const { total, items } =
      await listStoreEndorseRequestWithUserInfosByStoreID(
        storeId,
        isWaitAudit,
        {
          limit,
          offset,
          ts,
        }
      );

    ctx.body = {
      total,
      rows: items,
    };
  }
);

// // 移除品牌代言人申请
// router.delete("/brd/:brandId/endorseRequest/:endorseRequestId", async (ctx: AppCTX, next) => {
//   const { brandId, endorseRequestId } = ctx.params;
//   const { userId } = ctx;
//   //2 需要发送异步消息给代言人申请系统
//   ctx.body = {
//     brandId,
//     userId, //操作人
//     endorseRequestId,
//   };
// });

// 审核品牌代言人申请
const audit = async (
  storeId: string,
  storeEndorseRequestId: string,
  auditResult: AuditResult
) => {
  const storeEndorseRequest = await auditStoreEndorseRequest({
    storeEndorseRequestId,
    audited: Date.now(),
    auditResult,
  });

  //2 根据sync_id发送异步消息给代言人申请系统
  return {
    ...storeEndorseRequest,
  };
};

// 审核通过门店代言人申请
router.post(
  "/sto/:storeId/endorseRequest/:storeEndorseRequestId/approve",
  async (ctx: AppCTX, next) => {
    const { storeId, storeEndorseRequestId } = ctx.params;
    ctx.body = await audit(
      storeId,
      storeEndorseRequestId,
      AuditResult.APPROVED
    );
  }
);

// 审核拒绝门店代言人申请
router.post(
  "/brd/:storeId/endorseRequest/:storeEndorseRequestId/reject",
  async (ctx: AppCTX, next) => {
    const { storeId, storeEndorseRequestId } = ctx.params;
    ctx.body = await audit(
      storeId,
      storeEndorseRequestId,
      AuditResult.REJECTED
    );
  }
);

export default router;
